import { computed, ref, watch, inject } from 'vue'
import { useBuildAttrsKeys, AConfigProviderTypes } from '@/components'

const useTableHttp = (
  tableProps: Record<string, any>,
  paramsConfig: Record<string, any>,
  requestFinally = () => {}
) => {
  if (!tableProps.http) {
    return {
      httpData: computed(() => tableProps.tableData),
      httpTotal: computed(() => tableProps.tableData.length || 0),
      loading: false
    }
  }

  const httpData = ref<any>([])
  const httpTotal = ref()
  const loading = ref(false)

  const attrs = inject<AConfigProviderTypes>(useBuildAttrsKeys)
  const { CETable } = attrs as any
  const { transform } = CETable

  const params = computed(() => {
    return {
      ...paramsConfig,
      ...tableProps.params
    }
  })

  const httpRequest = () => {
    loading.value = true
    tableProps
      .http(params.value)
      .then((res: any) => {
        const data = ref<Record<string, string>>({})
        if (res && Array.isArray(res.records)) {
          data.value = transform({ data: res.records, total: res.total })
          httpData.value = data.value.data
        } else {
          httpData.value = res.data
        }
        httpTotal.value =
          data.value.total || res.data.records.length || res.data.length
      })
      .catch(() => {
        httpData.value = []
        httpTotal.value = 0
      })
      .finally(() => {
        loading.value = false
        requestFinally()
      })
  }

  watch(
    () => params.value,
    () => {
      // 懒加载 --> 需要手动 加载, 自己修改 isReload 为 true
      if (tableProps.lazyLoad) return
      httpRequest()
    },
    {
      deep: true,
      immediate: true
    }
  )

  watch(
    () => tableProps.isReload,
    (newVal: boolean) => {
      if (newVal) httpRequest()
    }
  )

  return {
    httpData,
    httpTotal,
    loading
  }
}

export { useTableHttp }
